//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use actix_web::http::header::ContentType;
use actix_web::HttpResponse;
use actix_web::dev::ServiceResponse;
use actix_web::middleware::ErrorHandlerResponse;
use crate::core::errors::error::Result;
use minijinja::context;
use crate::core::service::template_service::get_template;
use crate::utils::string_utils::format_error_string;

pub async fn not_found() -> Result<HttpResponse> {
    let ctx = context!(
        error_message => "页面未找到",
    );
    let out = get_template("/default/error/404.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}


pub fn add_error_body<B: actix_web::body::MessageBody + 'static>(res: ServiceResponse<B>) -> actix_web::Result<ErrorHandlerResponse<B>> {
    let (req, res) = res.into_parts();

    match res.error() {
        Some(err) => {
            let error_message = err.to_string();
            let message = format_error_string(&error_message);
            let ctx = context!(
                error_message => message.get("msg"),
            );
            let template_url = match message.get("code").map(|s| s.as_str()) {
                Some("403") => "/default/error/403.html",
                Some("404") => "/default/error/404.html",
                _ => "/default/error/500.html",
            };
            let out = get_template(&template_url, ctx)?;
            let res = HttpResponse::Ok()
                .content_type(ContentType::html())
                .body(out);

            Ok(ErrorHandlerResponse::Response(ServiceResponse::new(req, res).map_into_boxed_body().map_into_right_body()))

        },
        None => Ok(ErrorHandlerResponse::Response(ServiceResponse::new(req, res).map_into_boxed_body().map_into_right_body())),
    }
}